package activity_provas;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Bundle;
import android.text.format.Time;
import android.util.TypedValue;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TableRow;
import android.widget.TimePicker;
import android.widget.Toast;

import com.adjt.droidsapiens.R;

import database.DatabaseConnector;

@SuppressLint("SimpleDateFormat")
public class ExibirProva extends Activity {
	
	Time time;
	Intent it;
	int semestreAtual;

	DatabaseConnector db;
	Cursor c;
	
	Button editar, excluir, salvar, cancelar, dataBtn, horaBtn;
	
	String tables = "Disciplina";
	String[] column = new String[]{"idDisciplina", "nome"};
	String where = "";
	String orderBy = "";
	
	int idAtividade;
	EditText nome, valor, local, data, hora;
	Spinner disciplinaSpinner;
	ArrayAdapter<String> disciplinaAdapter;
	Map<String, Integer> disciplinaMap = new HashMap<String, Integer>();
	
	int px, buttonPx;
	
	public static final int Date_dialog_id = 1;
	private int mYear, mMonth, mDay, mHour, mMinute;
	int Year, Month, Day, Hour, Minute;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_exibir_prova);
		
		Resources r = getResources();
		buttonPx = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 100, r.getDisplayMetrics());
		px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,75, r.getDisplayMetrics());
		
		idAtividade = getIntent().getIntExtra("idAtividade", 0);
		semestreAtual = getIntent().getIntExtra("semestreAtual", 0);
		nome = (EditText) findViewById(R.id.ExibirProva_nome);
		valor = (EditText) findViewById(R.id.ExibirProva_valor);
		local = (EditText) findViewById(R.id.ExibirProva_local);
		data = (EditText) findViewById(R.id.ExibirProva_data);
		data.setKeyListener(null);
		hora = (EditText) findViewById(R.id.ExibirProva_hora);
		hora.setKeyListener(null);
		disciplinaSpinner = (Spinner) findViewById(R.id.ExibirProva_disciplina);
		editar = (Button) findViewById(R.id.ExibirProva_editar);
		editar.setWidth(buttonPx);
		excluir = (Button) findViewById(R.id.ExibirProva_excluir);
		excluir.setWidth(buttonPx);
		horaBtn = (Button) findViewById(R.id.ExibirProva_horaDialog);
		dataBtn = (Button) findViewById(R.id.ExibirProva_dataDialog);
		
		db = new DatabaseConnector(getBaseContext());
		begin();
	}
	
	public void begin(){
		db.open();
		c = db.buscar(tables, column, where, orderBy);
		if(c.getCount() > 0){
			disciplinaAdapter = new ArrayAdapter<String>(getBaseContext(), android.R.layout.simple_spinner_item);
			int idDisciplina = 0;
			String nomeDisciplina = "";
			if(c.getCount() > 0) {
				while(c.moveToNext()) {
					idDisciplina = c.getInt(c.getColumnIndex("idDisciplina"));
					nomeDisciplina = c.getString(c.getColumnIndex("nome"));
					disciplinaMap.put(nomeDisciplina, idDisciplina);
					disciplinaAdapter.add(nomeDisciplina);
				}
				disciplinaSpinner.setAdapter(disciplinaAdapter);
				
				tables = "Atividade";
				column = new String[]{"nome", "local", "valor", "data", "idDisciplina"};
				where = "idAtividade = " + idAtividade;
				
				Cursor cursor = db.buscar(tables, column, "", "");
				cursor.moveToNext();
				
				nome.setText(cursor.getString(cursor.getColumnIndex("nome")));
				nome.setEnabled(false);
				local.setText(cursor.getString(cursor.getColumnIndex("local")));
				local.setEnabled(false);
				valor.setText(String.valueOf(cursor.getInt(cursor.getColumnIndex("valor"))));
				valor.setEnabled(false);
				
				horaBtn.setEnabled(false);
				dataBtn.setEnabled(false);
				
				long dataCompleta = cursor.getLong(cursor.getColumnIndex("data"));
				Time timeBD = new Time(Time.getCurrentTimezone());
		        timeBD.normalize(true);
		        timeBD.set(dataCompleta);
		        
		        Year = timeBD.year;
				Month = timeBD.month;
				Day = timeBD.monthDay;
				Hour = timeBD.hour;
				Minute = timeBD.minute;
				
				SimpleDateFormat dataf = new SimpleDateFormat("dd/MM/yyyy");
				String datac = dataf.format(new Date(dataCompleta));
				data.setText(datac);
				data.setEnabled(false);
				
				SimpleDateFormat horaf = new SimpleDateFormat("HH:mm");
				String horac = horaf.format(new Date(dataCompleta));
				hora.setText(horac);
				hora.setEnabled(false);
				
				disciplinaSpinner.setSelection(disciplinaAdapter.getPosition(nomeDisciplina));
				disciplinaSpinner.setEnabled(false);
				
				salvar = new Button(this);
				salvar.setText(R.string.salvar);
				salvar.setWidth(buttonPx);
				salvar.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Salvar(v);
					}
				});
		
				cancelar = new Button(this);
				cancelar.setText(R.string.cancelar);
				cancelar.setWidth(buttonPx);
				cancelar.setOnClickListener(new OnClickListener() {
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						Cancelar(v);
					}
				});
				
			}else {
				Toast.makeText(getBaseContext(),R.string.Toast_erroPrecisaDisciplinaCadastrada, Toast.LENGTH_LONG).show();
				Intent it = new Intent(getBaseContext(), Provas.class);
				startActivity(it);
				it.putExtra("semestreAtual", this.semestreAtual);
				finish();
			}
		}else {
			Toast.makeText(getBaseContext(), R.string.Toast_provaNaoEncontradaBD,Toast.LENGTH_SHORT).show();
			it = new Intent(getBaseContext(), Provas.class);
	   		it.putExtra("semestreAtual", semestreAtual);
	   		startActivity(it);
	   		finish();
		}
		db.close();
	}
	
	public void getTime(){
		time = new Time(Time.getCurrentTimezone());
		time.normalize(true);
		time.setToNow();
		mYear = time.year;
		mMonth = time.month;
		mDay = time.monthDay;
		mHour = time.hour;
		mMinute = time.minute;
	}
	
	@Override
	public void onBackPressed(){
		it = new Intent(getBaseContext(), Provas.class);
		it.putExtra("semestreAtual", semestreAtual);
		startActivity(it);
		finish();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.nova_prova, menu);
		return true;
	}
	
	public void DataDialog(View v) {
		getTime();
		DatePickerDialog DPD = new DatePickerDialog(ExibirProva.this,DateSetListener, mYear, mMonth, mDay);
		DPD.show();
	}

	public void HoraDialog(View v) {
		getTime();
		TimePickerDialog TPD = new TimePickerDialog(ExibirProva.this,HourSetListener, mHour, mMinute, true);
		TPD.show();
	}

	@Override
	@Deprecated
	protected void onPrepareDialog(int id, Dialog dialog) {
		// TODO Auto-generated method stub
		super.onPrepareDialog(id, dialog);

		((DatePickerDialog) dialog).updateDate(mYear, mMonth, mDay);
		
		((TimePickerDialog) dialog).updateTime(mHour, mMinute);

	}

	private DatePickerDialog.OnDateSetListener DateSetListener = new DatePickerDialog.OnDateSetListener() {
		public void onDateSet(DatePicker view, int year, int monthOfYear,
				int dayOfMonth) {
			Year = year;
			Month = monthOfYear;
			Day = dayOfMonth;
			updateDisplayDate();
		}
	};

	private TimePickerDialog.OnTimeSetListener HourSetListener = new TimePickerDialog.OnTimeSetListener() {
		public void onTimeSet(TimePicker view, int hour, int minute) {
			Hour = hour;
			Minute = minute;
			updateDisplayHour();
		}
	};

	private void updateDisplayDate() {
		// TODO Auto-generated method stub
		String month = "" + (Month + 1);
		if (Month < 9)
			month = "0" + (Month + 1);
		String day = "" + Day;
		if (Day < 10)
			day = "0" + Day;
		// Month is 0 based so add 1
		data.setText(new StringBuilder().append(day).append("/").append(month)
				.append("/").append(Year));
	}

	private void updateDisplayHour() {
		// TODO Auto-generated method stub
		String hour = "" + Hour;
		if (Hour < 10)
			hour = "0" + Hour;
		String minute = "" + Minute;
		if (Minute < 10)
			minute = "0" + Minute;
		hora.setText(new StringBuilder().append(hour).append(":")
				.append(minute));
	}
	
	public void Editar(View v) {
		nome.setEnabled(true);
		local.setEnabled(true);
		valor.setEnabled(true);
		data.setEnabled(true);
		hora.setEnabled(true);
		horaBtn.setEnabled(true);
		dataBtn.setEnabled(true);
		disciplinaSpinner.setEnabled(true);
		TableRow tr = (TableRow) findViewById(R.id.ExibirProvas_buttonsTableRow);
		tr.removeAllViews();
		tr.addView(salvar);
		tr.addView(cancelar);
	}
	
	public void Salvar(View v) {
		 DatabaseConnector db = new DatabaseConnector(getBaseContext());
		 db.open();	 
		 tables = "Atividade";
		 ContentValues valores = new ContentValues();
		 valores.put("nome", nome.getText().toString());
		 valores.put("local", local.getText().toString());
		 Time tempo = new Time();
		 tempo.set(0, Minute, Hour, Day, Month, Year);
		 tempo.normalize(true);
		 valores.put("data", tempo.toMillis(true));
		 if(valor.getTextSize() > 0) {
			 valores.put("valor", Integer.parseInt(valor.getText().toString()));
		 }
		 valores.put("idDisciplina", disciplinaMap.get(disciplinaSpinner.getSelectedItem().toString()));
	 
		 db.atualizar(tables, valores, "idAtividade = " + idAtividade);
	
		 it = new Intent(getBaseContext(), Provas.class);
		 it.putExtra("semestreAtual", semestreAtual);
		 startActivity(it);
		 finish();
	}

	public void Cancelar(View v) {
		begin();
		TableRow tr = (TableRow) findViewById(R.id.ExibirProvas_buttonsTableRow);
		tr.removeAllViews();
		tr.addView(editar);
		tr.addView(excluir);
	}

	public void Excluir(View v) {
		AlertDialog.Builder builder = new AlertDialog.Builder(ExibirProva.this);
		builder.setMessage(R.string.ExibirProva_excluirAlertDialog).setTitle(R.string.excluirProva);
		
		builder.setPositiveButton(R.string.sim, new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	               // User clicked OK button
	        	   db = new DatabaseConnector(getBaseContext());
	   				db.open();
		       		db.deletar("Atividade", "idAtividade = " + idAtividade);
		       		Toast.makeText(getBaseContext(),R.string.Toast_provaExcluidaSucesso, Toast.LENGTH_SHORT).show();
		       		onBackPressed();
		       		db.close();
	           }
	       });
		
		builder.setNegativeButton(R.string.nao, new DialogInterface.OnClickListener() {
	           public void onClick(DialogInterface dialog, int id) {
	               // User cancelled the dialog
	           }
	       });
		
		AlertDialog dialog = builder.create();
		dialog.show();
	}

}
